package com.ashlikun.utils.ui.status

import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.annotation.TargetApi
import android.app.Activity
import android.content.Context
import android.content.res.Configuration
import android.content.res.Resources
import android.graphics.Color
import android.graphics.Insets
import android.os.Build
import android.view.View
import android.view.ViewGroup.MarginLayoutParams
import android.view.Window
import android.view.WindowManager
import androidx.activity.ComponentActivity
import androidx.annotation.ColorInt
import androidx.appcompat.widget.Toolbar
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.core.view.ViewCompat
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat
import androidx.core.view.updateLayoutParams
import androidx.core.view.updatePadding
import com.ashlikun.utils.AppUtils
import com.ashlikun.utils.other.RomUtils.isHuawei
import com.ashlikun.utils.other.RomUtils.isMeizu
import com.ashlikun.utils.other.RomUtils.isXiaomi
import com.ashlikun.utils.other.RomUtils.isZTKC2016
import com.ashlikun.utils.other.RomUtils.isZUKZ1
import com.ashlikun.utils.ui.ScreenUtils
import com.ashlikun.utils.ui.extend.getActivity
import com.ashlikun.utils.ui.extend.getUserRootView
import com.ashlikun.utils.ui.extend.setLightNavigationBars
import com.ashlikun.utils.ui.extend.setLightStatusBars
import com.ashlikun.utils.ui.extend.showStatusBar
import com.ashlikun.utils.ui.resources.ColorUtils
import com.google.android.material.appbar.AppBarLayout
import com.google.android.material.appbar.AppBarLayout.OnOffsetChangedListener
import com.google.android.material.appbar.CollapsingToolbarLayout
import java.util.Objects

fun Resources.systemBarStyleAutoX(@ColorInt scrim: Int, @ColorInt darkScrim: Int): SystemBarStyle {
    return if ((configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK) == Configuration.UI_MODE_NIGHT_YES) {
        SystemBarStyle.dark(scrim)
    } else {
        SystemBarStyle.light(scrim, darkScrim)
    }
}

val hasSystemEdgeToEdgeImpl by lazy {
    try {
        //判断是否有EdgeToEdge.kt类，androidx.core:core-ktx:1.16.0和 androidx.activity:activity-ktx:1.12.0-alpha05 之后才有
        //如果没有，则使用我们复制过来的
        val clazz = Class.forName("androidx.activity.EdgeToEdgeImpl")
        val clazz2 = Class.forName("androidx.activity.EdgeToEdgeApi35")
        true
    } catch (e: NoClassDefFoundError) {
        false
    }
}

/**
 * 开启边到边
 * @param isSetView 是否设置View 间距
 * @param statusBarStyle 状态栏样式
 * @param navigationBarStyle 导航栏样式
 * @param top 是否顶部间距
 * @param bottom 是否底部间距
 */
fun ComponentActivity.enableEdgeToEdgeX(
    isSetView: Boolean = true,
    top: Boolean = true,
    bottom: Boolean = true,
    consume: Boolean = true,
    statusBarStyle: SystemBarStyle = resources.systemBarStyleAutoX(Color.TRANSPARENT, Color.TRANSPARENT),
    navigationBarStyle: SystemBarStyle = resources.systemBarStyleAutoX(Color.TRANSPARENT, Color.TRANSPARENT),
) {
    enableEdgeToEdge(statusBarStyle, navigationBarStyle)
    if (isSetView) {
        getUserRootView().setSafeAreaPadding(top = top, bottom = bottom, consume = consume)
    }
//    if (StatusBarCompat.isAndroid15) {
//        // 设置系统栏透明
//        window.statusBarColor = Color.TRANSPARENT
//        window.navigationBarColor = Color.TRANSPARENT
//        if (isSetView) {
////            getUserRootView()?.fitsSystemWindows  = true
//            getUserRootView().setSfeAreaPadding(top = top, bottom = bottom)
//        }
//    } else {
////        window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
////        window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION)
//        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
//        window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
//        if (isSetTop) {
//            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
//            window.statusBarColor = Color.TRANSPARENT
//            window.decorView.systemUiVisibility = window.decorView.systemUiVisibility or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
//        }
//        if (isSetBottom) {
//            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION)
//            window.navigationBarColor = Color.TRANSPARENT
//            window.decorView.systemUiVisibility = window.decorView.systemUiVisibility or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
//        }
//        window.decorView.fitsSystemWindows = false
//        window.decorView.requestApplyInsets()
//        if (isSetView) {
//            getUserRootView().setSfeAreaPadding(top = top, bottom = bottom)
//        }
//    }

}

/**
 * 参照WindowCompat.enableEdgeToEdge
 * Enables the content of the given [window][Window] to reach the edges of the window
 * without getting inset by system insets, and prevents the framework from placing color views
 * behind system bars.
 *
 * @param window the given window.
 */
fun Window.enableEdgeToEdge(
    statusBarStyle: SystemBarStyle = context.resources.systemBarStyleAutoX(Color.TRANSPARENT, Color.TRANSPARENT),
    navigationBarStyle: SystemBarStyle = context.resources.systemBarStyleAutoX(Color.TRANSPARENT, Color.TRANSPARENT),
) {
    val statusBarIsDark = statusBarStyle.detectDarkMode(context.resources)
    val navigationBarIsDark = navigationBarStyle.detectDarkMode(context.resources)
    // This triggers the initialization of the decor view here to prevent the attributes set by
    // this method from getting overwritten by the initialization later.
    decorView

    WindowCompat.setDecorFitsSystemWindows(this, false)
    this.statusBarColor = Color.TRANSPARENT
    this.navigationBarColor = Color.TRANSPARENT
    if (Build.VERSION.SDK_INT >= 28) {
        val newMode = if (Build.VERSION.SDK_INT >= 30)
            WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS
        else
            WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
        val attrs = this.attributes
        if (attrs.layoutInDisplayCutoutMode != newMode) {
            attrs.layoutInDisplayCutoutMode = newMode
            this.attributes = attrs
        }
    }
    if (Build.VERSION.SDK_INT >= 29) {
        this.isStatusBarContrastEnforced = false
        this.isNavigationBarContrastEnforced = false
    }
    WindowInsetsControllerCompat(this, this.decorView).run {
        isAppearanceLightStatusBars = !statusBarIsDark
        isAppearanceLightNavigationBars = !navigationBarIsDark
    }
}

/**
 * 设置控件Margin 顶部留出间距
 */
fun Activity?.setSafeAreaMargin(top: Boolean = true, bottom: Boolean = true) {
    getUserRootView().setSafeAreaMargin(top = top, bottom = bottom)
}

fun View?.setSafeAreaMargin(top: Boolean = true, bottom: Boolean = true, consume: Boolean = true, isUseRootView: Boolean = false) {
    if (this == null) return
    val targetView = if (isUseRootView) context.getActivity()?.getUserRootView() ?: this else this
    //这里会动态返回用户设置的底部高度
    ViewCompat.setOnApplyWindowInsetsListener(targetView) { view, insets ->
        val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
//        val statusBars = insets.getInsets(WindowInsetsCompat.Type.statusBars())
//        val navigationBars = insets.getInsets(WindowInsetsCompat.Type.navigationBars())
        //更新背景视图位置和尺寸
        view.updateLayoutParams<MarginLayoutParams> {
            if (top) topMargin = systemBars.top
            if (bottom) bottomMargin = systemBars.bottom
        }
        //返回消耗的insets
        if (consume) insets.replaceSystemWindowInsets(systemBars.left, if (top) 0 else systemBars.top, systemBars.right, if (bottom) 0 else systemBars.bottom) else insets

    }
}

/**
 * 设置安全区边距
 */
fun Activity?.setSafeAreaPadding(top: Boolean = true, bottom: Boolean = true) {
    getUserRootView().setSafeAreaPadding(top = top, bottom = bottom)
}

fun View?.setSafeAreaPadding(top: Boolean = true, bottom: Boolean = true, consume: Boolean = true, isUseRootView: Boolean = false) {
    if (this == null) return
    val targetView = if (isUseRootView) context.getActivity()?.getUserRootView() ?: this else this
    //这里会动态返回用户设置的底部高度
    ViewCompat.setOnApplyWindowInsetsListener(targetView) { _, insets ->
        val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
//        val statusBars = insets.getInsets(WindowInsetsCompat.Type.statusBars())
//        val navigationBars = insets.getInsets(WindowInsetsCompat.Type.navigationBars())
        //更新背景视图位置和尺寸
        if (top) updatePadding(top = systemBars.top)
        if (bottom) updatePadding(bottom = systemBars.bottom)
        //返回消耗的insets
        if (consume) {
            insets.replaceSystemWindowInsets(systemBars.left, if (top) 0 else systemBars.top, systemBars.right, if (bottom) 0 else systemBars.bottom)
        } else {
            insets
        }
    }
}

/**
 * 设置状态栏空View的高度
 * 设置页面顶部一个null的view的高度，
 * 只有当设置状态栏透明的时候用到,因为此时跟布局会顶到状态栏里面
 */
fun View?.setSafeAreaTop(consume: Boolean = true, isUseRootView: Boolean = false) {
    if (this == null) return
    val targetView = if (isUseRootView) context.getActivity()?.getUserRootView() ?: this else this
    //这里会动态返回用户设置的底部高度
    ViewCompat.setOnApplyWindowInsetsListener(targetView) { view, insets ->
        val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
        //更新背景视图位置和尺寸
        updateLayoutParams {
            height = systemBars.top
        }
        //返回消耗的insets
        if (consume) insets.replaceSystemWindowInsets(systemBars.left, 0, systemBars.right, systemBars.bottom) else insets
    }
}

fun View?.setSafeAreaBottom(consume: Boolean = true, isUseRootView: Boolean = false) {
    if (this == null) return
    val targetView = if (isUseRootView) context.getActivity()?.getUserRootView() ?: this else this
    //这里会动态返回用户设置的底部高度
    ViewCompat.setOnApplyWindowInsetsListener(targetView) { view, insets ->
        val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
        //更新背景视图位置和尺寸
        updateLayoutParams {
            height = systemBars.bottom
        }
        //返回消耗的insets
        if (consume) insets.replaceSystemWindowInsets(systemBars.left, systemBars.top, systemBars.right, 0) else insets
    }
}

/**
 * 设置状态栏字体颜色为深色
 */
fun Activity.setStatusDarkColor() {
    setStatusTextColor(true)
}

fun Activity.setNavigationDarkColor() {
    setNavigationTextColor(true)
}

/**
 * 设置状态栏字体浅色
 */
fun Activity.setStatusLightColor() {
    setStatusTextColor(false)
}

fun Activity.setNavigationLightColor() {
    setNavigationTextColor(false)
}

fun Activity.setStatusTextColor(dark: Boolean) {
    window.setLightStatusBars(dark)
    //小米
    if (isXiaomi) {
        StatusBarCompat.miuiSetStatusBarLightMode(window, dark)
    }
    //魅族
    if (isMeizu) {
        StatusBarCompat.flymeSetStatusBarLightMode(window, dark)
    }
}

fun Activity.setNavigationTextColor(dark: Boolean) {
    window.setLightNavigationBars(dark)
}

/**
 * 根据颜色值自动设置状态栏字体颜色
 */
fun Activity.setAutoStatusTextColor(color: Int) {
    if (ColorUtils.isColorDark(color)) {
        //浅色文字
        setStatusLightColor()
    } else {
        //深色文字
        setStatusDarkColor()
    }
}

fun Activity.setAutoNavigationTextColor(color: Int) {
    if (ColorUtils.isColorDark(color)) {
        //浅色文字
        setNavigationLightColor()
    } else {
        //深色文字
        setNavigationDarkColor()
    }
}

/**
 * 兼容设置状态栏颜色,要在设置完布局后设置
 * 本方法会自动设置状态栏字体颜色
 */
fun Activity.setStatusBarColor(statusColor: Int, isNotch: Boolean = StatusBarCompat.isNotchFullscreen) {
    //5.0以下不设置
    var statusColor = statusColor
    if (isNotch) {
        setNotch()
    }
    if (StatusBarCompat.isAndroid15) {
        setupEdgeToEdge()
    } else {
        if (!StatusBarCompat.isSetStatusTextColor) {
            //不能设置状态栏字体颜色时候
            if (!ColorUtils.isColorDark(statusColor)) {
                //颜色浅色,设置半透明
                statusColor = ColorUtils.blendColor(StatusBarCompat.HALF_COLOR, statusColor)
            }
        }
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
        window.statusBarColor = statusColor
        window.showStatusBar()
        window.decorView.fitsSystemWindows = false
        window.decorView.requestApplyInsets()
    }
    setAutoStatusTextColor(statusColor)
}

fun Activity.setStatusBarColorWhite() {
    setStatusBarColor(Color.WHITE)
}

fun Activity.setStatusBarColorBlack() {
    setStatusBarColor(Color.BLACK)
}

/**
 * 刘海屏适配
 */
fun Activity.setNotch() {
    if (NotchHelper.isNotchOfficialSupport()) {
        StatusBarCompat.handleDisplayCutoutMode(window)
    }
}


/**
 * Android 15+ Edge-to-Edge 设置
 */
fun Activity.setupEdgeToEdge() {
    // 设置系统栏透明
    window.statusBarColor = Color.TRANSPARENT
    window.navigationBarColor = Color.TRANSPARENT
//        window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)

    // 设置OnApplyWindowInsetsListener
    getUserRootView()?.fitsSystemWindows = true
}


/**
 * 使用跟布局插入状态栏
 * 这里没有设置状态栏字体颜色
 * 一般用于这个页面有类似微信的查看大图，解决返回的时候抖动问题
 */
fun Activity.setFitsSystemWindows() {
    window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
    window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION)
    window.decorView.fitsSystemWindows = false
    window.decorView.requestApplyInsets()
}


/**
 * 设置底部导航栏透明
 *
 * @param isTransparent 是否透明
 */
fun Activity.setTransparentNavigationBar(isTransparent: Boolean = true) {
    if (window != null) {
        if (isTransparent) {
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION)
        } else {
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION)
        }
    }
}

/**
 * 设置透明状态栏时候，顶部的padding
 *
 * @param isNeedAndroidMHalf 6.0以下是否绘制半透明,因为不能设置状态栏字体颜色
 */
fun Activity.setTransparentStatusBar(isNeedAndroidMHalf: Boolean = false, isNotch: Boolean = StatusBarCompat.isNotchFullscreen) {
    if (isNotch) {
        setNotch()
    }
    if (StatusBarCompat.isAndroid15) {
        // 设置系统栏透明
        window.statusBarColor = Color.TRANSPARENT
        window.navigationBarColor = Color.TRANSPARENT
    } else {
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
        if (isNeedAndroidMHalf && !StatusBarCompat.isSetStatusTextColor) {
            //不能设置状态栏字体颜色时候
            window.statusBarColor = StatusBarCompat.HALF_COLOR
        } else {
            window.statusBarColor = Color.TRANSPARENT
        }
        //透明全屏
        window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
        window.decorView.fitsSystemWindows = false
        window.decorView.requestApplyInsets()
    }
}

/**
 * 设置透明的状态栏，实际布局内容在状态栏里面
 */
fun Activity.setStatusBarColorForCollapsingToolbar(
    appBarLayout: AppBarLayout, collapsingToolbarLayout: CollapsingToolbarLayout, toolbar: Toolbar, statusColor: Int, isNotch: Boolean = StatusBarCompat.isNotchFullscreen
) {
    if (isNotch) {
        setNotch()
    }
    window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
    window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
    window.statusBarColor = Color.TRANSPARENT
    window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_VISIBLE
    ViewCompat.setOnApplyWindowInsetsListener(collapsingToolbarLayout) { v, insets -> insets }
    window.decorView.fitsSystemWindows = false
    window.decorView.requestApplyInsets()
    (appBarLayout.parent as View).fitsSystemWindows = false
    appBarLayout.fitsSystemWindows = false
    toolbar.fitsSystemWindows = false
    if (toolbar.tag == null) {
        val lp = toolbar.layoutParams as CollapsingToolbarLayout.LayoutParams
        val statusBarHeight = ScreenUtils.statusBarHeight
        lp.height += statusBarHeight
        toolbar.layoutParams = lp
        toolbar.setPadding(
            toolbar.paddingLeft, toolbar.paddingTop + statusBarHeight, toolbar.paddingRight, toolbar.paddingBottom
        )
        toolbar.tag = true
    }
    val behavior = (appBarLayout.layoutParams as CoordinatorLayout.LayoutParams).behavior
    if (behavior != null && behavior is AppBarLayout.Behavior) {
        val verticalOffset = behavior.topAndBottomOffset
        if (Math.abs(verticalOffset) > appBarLayout.height - collapsingToolbarLayout.scrimVisibleHeightTrigger) {
            window.statusBarColor = statusColor
        } else {
            window.statusBarColor = Color.TRANSPARENT
        }
    } else {
        window.statusBarColor = Color.TRANSPARENT
    }
    collapsingToolbarLayout.fitsSystemWindows = false
    appBarLayout.addOnOffsetChangedListener(OnOffsetChangedListener { appBarLayout, verticalOffset ->
        if (Math.abs(verticalOffset) > appBarLayout.height - collapsingToolbarLayout.scrimVisibleHeightTrigger) {
            if (window.statusBarColor != statusColor) {
                StatusBarCompat.startColorAnimation(
                    window.statusBarColor, statusColor, collapsingToolbarLayout.scrimAnimationDuration, window
                )
            }
        } else {
            if (window.statusBarColor != Color.TRANSPARENT) {
                StatusBarCompat.startColorAnimation(
                    window.statusBarColor, Color.TRANSPARENT, collapsingToolbarLayout.scrimAnimationDuration, window
                )
            }
        }
    })
    collapsingToolbarLayout.getChildAt(0).fitsSystemWindows = false
    collapsingToolbarLayout.setStatusBarScrimColor(statusColor)
}

/**
 * @author　　: 李坤
 * 创建时间: 2021.12.14 17:02
 * 邮箱　　：496546144@qq.com
 *
 * 功能介绍：状态栏的工具
 */

object StatusBarCompat {
    //是否适配刘海屏
    //在非全屏模式下，这个方法（LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES）在部分10.0手机会导致水波纹卡顿，所以不用
    var isNotchFullscreen = true
    val isAndroid15
        get() = AppUtils.app.applicationInfo.targetSdkVersion >= 35 && Build.VERSION.SDK_INT >= 35

    /**
     * 是否设置半透明颜色
     * 6.0以下不能设置状态栏文字颜色,这里处理,5.0-6.0已经在设置状态栏颜色的时候设置了
     */
    val isAndroid5Or6: Boolean
        get() = Build.VERSION.SDK_INT < Build.VERSION_CODES.M && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP

    /**
     * 半透明颜色值
     */
    const val HALF_COLOR = -0x77555556
    private var sAnimator: ValueAnimator? = null


    /**
     * 获取底部导航栏高度
     */
    fun getNavigationHeight(): Int {
        var result = 0
        val resourceId = AppUtils.defaultResources.getIdentifier("navigation_bar_height", "dimen", "android")
        if (resourceId > 0) {
            result = AppUtils.defaultResources.getDimensionPixelSize(resourceId)
        }
        return result
    }


    /**
     * 当使用collapsingToolbarLayout布局时，使用ValueAnimator来改变statusBarColor
     */
    @SuppressLint("NewApi")
    fun startColorAnimation(startColor: Int, endColor: Int, duration: Long, window: Window?) {
        sAnimator?.cancel()
        sAnimator = ValueAnimator.ofArgb(startColor, endColor).setDuration(duration)
        sAnimator?.addUpdateListener { valueAnimator ->
            if (window != null) {
                window.statusBarColor = (valueAnimator.animatedValue as Int)
            }
        }
        sAnimator?.addListener(object : AnimatorListenerAdapter() {
            override fun onAnimationCancel(animation: Animator) {
                super.onAnimationCancel(animation)
                sAnimator = null
            }

            override fun onAnimationEnd(animation: Animator) {
                super.onAnimationEnd(animation)
                sAnimator = null
            }
        })
        sAnimator?.start()
    }


    /**
     * 是否可以设置状态栏字体颜色
     */
    val isSetStatusTextColor: Boolean
        // Essential Phone 在 Android 8 之前沉浸式做得不全，系统不从状态栏顶部开始布局却会下发 WindowInsets
        get() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && (isHuawei || isMeizu || Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !(isZUKZ1 || isZTKC2016))


    /**
     * 设置状态栏图标为深色和魅族特定的文字风格
     * 可以用来判断是否为Flyme用户
     *
     * @param window 需要设置的窗口
     * @param dark   是否把状态栏文字及图标颜色设置为深色
     * @return boolean 成功执行返回true
     */
    fun flymeSetStatusBarLightMode(window: Window, dark: Boolean): Boolean {
        var result = false
        try {
            val lp = window.attributes
            val darkFlag = WindowManager.LayoutParams::class.java.getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON")
            val meizuFlags = WindowManager.LayoutParams::class.java.getDeclaredField("meizuFlags")
            darkFlag.isAccessible = true
            meizuFlags.isAccessible = true
            val bit = darkFlag.getInt(null)
            var value = meizuFlags.getInt(lp)
            value = if (dark) {
                value or bit
            } else {
                value and bit.inv()
            }
            meizuFlags.setInt(lp, value)
            window.attributes = lp
            result = true
        } catch (e: Exception) {
        }
        return result
    }

    /**
     * 需要MIUIV6以上
     *
     * @param window
     * @param dark   是否把状态栏文字及图标颜色设置为深色
     * @return boolean 成功执行返回true
     */
    fun miuiSetStatusBarLightMode(window: Window, dark: Boolean): Boolean {
        var result = false
        val clazz: Class<*> = window.javaClass
        try {
            var darkModeFlag = 0
            val layoutParams = Class.forName("android.view.MiuiWindowManager\$LayoutParams")
            val field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE")
            darkModeFlag = field.getInt(layoutParams)
            val extraFlagField = clazz.getMethod(
                "setExtraFlags", Int::class.javaPrimitiveType, Int::class.javaPrimitiveType
            )
            if (dark) {
                //状态栏透明且黑色字体
                extraFlagField.invoke(window, darkModeFlag, darkModeFlag)
            } else {
                //清除黑色字体
                extraFlagField.invoke(window, 0, darkModeFlag)
            }
            result = true
        } catch (e: Exception) {
        }
        return result
    }

    /**
     * 刘海屏状态栏
     *
     * @param window
     */
    @TargetApi(28)
    fun handleDisplayCutoutMode(window: Window) {
//            val decorView = window.decorView
//            if (decorView != null) {
//                if (ViewCompat.isAttachedToWindow(decorView)) {
//                    realHandleDisplayCutoutMode(window, decorView)
//                } else {
//                    decorView.addOnAttachStateChangeListener(object :
//                        View.OnAttachStateChangeListener {
//                        override fun onViewAttachedToWindow(v: View) {
//                            v.removeOnAttachStateChangeListener(this)
//                            realHandleDisplayCutoutMode(window, v)
//                        }
//
//                        override fun onViewDetachedFromWindow(v: View) {}
//                    })
//                }
//            }
        realHandleDisplayCutoutMode(window)
    }

    /**
     * 刘海屏状态栏
     */
    @TargetApi(28)
    private fun realHandleDisplayCutoutMode(window: Window) {
        val params = window.attributes
        //该窗口始终允许延伸到屏幕短边上的DisplayCutout区域
        //在非全屏模式下，这个方法（LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES）在部分10.0手机会导致水波纹卡顿，所以不用
        params.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
        window.attributes = params
    }

    /**
     * 获取当前状态栏颜色（多种方法）
     */
    @ColorInt
    fun getStatusBarColor(context: Context): Int? {
        val activity = context as? Activity ?: return Color.TRANSPARENT
        // 直接通过 Window 获取（API 21+）
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            val windowStatusBarColor = activity.window.statusBarColor
            if (windowStatusBarColor != Color.TRANSPARENT) {
                return windowStatusBarColor
            }
        }

        // 通过主题属性获取
        val themeStatusBarColor = getThemeStatusBarColor(context)
        if (themeStatusBarColor != Color.TRANSPARENT) {
            return themeStatusBarColor
        }
        // 检测 AppBarLayout 背景色
//        return detectAppBarStatusBarColor(activity)
        return null
    }

    /**
     * 从主题中获取状态栏颜色
     */
    @ColorInt
    fun getThemeStatusBarColor(context: Context): Int {
        val attrs = intArrayOf(android.R.attr.statusBarColor)
        val typedArray = context.obtainStyledAttributes(attrs)
        val color = try {
            typedArray.getColor(0, Color.TRANSPARENT)
        } finally {
            typedArray.recycle()
        }
        return color
    }
}
